﻿using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ZhongJia.Lock.Infrastructure.Data;

namespace ZhongJia.Lock.DataMigration.Seeders
{
    public class IdentitySeeder : ISeeder
    {
        private readonly ConfigurationDbContext _dbContext;
        private readonly PersistedGrantDbContext _pdbContext;

        public IdentitySeeder(ConfigurationDbContext dbContext,
            PersistedGrantDbContext pdbContext)
        {
            _dbContext = dbContext;
            _pdbContext = pdbContext;
        }

        public Task Seed()
        {
            _dbContext.Database.Migrate();
            _pdbContext.Database.Migrate();
            foreach (var client in IdentityServerConfig.GetClients())
            {
                _dbContext.Clients.Add(client.ToEntity());
            }
            foreach (var resource in IdentityServerConfig.GetIdentityResources())
            {
                _dbContext.IdentityResources.Add(resource.ToEntity());
            }
            foreach (var resource in IdentityServerConfig.GetApiResources())
            {
                _dbContext.ApiResources.Add(resource.ToEntity());
            }
            return _dbContext.SaveChangesAsync();
        }
    }
}
